package com.ywz.framework.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ywz.framework.security.CustomUser;
import com.ywz.project.base.system.entity.TSysPermission;
import com.ywz.project.base.system.entity.TSysRole;
import com.ywz.project.base.system.entity.TSysUser;
import com.ywz.project.base.system.service.TSysPermissionService;
import com.ywz.project.base.system.service.TSysRoleService;
import com.ywz.project.base.system.service.TSysUserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述 -> 实现UserDetailsService接口，重写方法
 *
 * @Author: ywz
 * @Date: 2024/07/28
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private TSysUserService sysUserService;
    @Resource
    private TSysRoleService sysRoleService;
    @Resource
    private TSysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<TSysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSysUser::getUsername, username);
        queryWrapper.eq(TSysUser::getIsDeleted, 0);
        TSysUser sysUser = sysUserService.getOne(queryWrapper, false);
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException("用户名不存在！");
        }
        if (sysUser.getStatus() == 0)
            throw new RuntimeException("账户未启用，请联系管理员！");

        // 获取当前登录的角色
        List<TSysRole> roleList = sysRoleService.getRoleListByUserId(sysUser.getId());
        // 获取当前登录的权限
        List<Integer> roleIds = roleList.stream().map(TSysRole::getId).collect(Collectors.toList());
        List<TSysPermission> permissionList;
        // 如果是超级管理员，获取所有权限
        if (roleIds.contains(-1)) {
            permissionList = sysPermissionService.getPermissionList();
        } else {
            permissionList = sysPermissionService.getPermissionListByRoleIds(roleIds);
        }
        // 将角色和权限封装到CustomUser中
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (TSysRole role : roleList) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleType()));
        }
        for (TSysPermission permission : permissionList) {
            authorities.add(new SimpleGrantedAuthority(permission.getPermissionName()));
        }
        return new CustomUser(sysUser, authorities);
    }
}